//
//  Plane.m
//  HKOCRuler
//
//  Created by lbxia on 2018/11/23.
//  Copyright © 2018年 lbx. All rights reserved.
//

#import "Plane.h"

@implementation Plane

- (instancetype)init
{
    if (self = [super init]) {
        
        self.occlusionPlaneVerticalOffset = -0.01;
    }
    return self;
}

- (instancetype)initWithAnchor:(ARPlaneAnchor*)anchor showDebugVisualization:(BOOL)showDebugVisualization
{
    self = [self init];
    self.anchor = anchor;
    [self showDebugVisualization:showDebugVisualization];
    
    [self createOcclusionNode];
    
    return self;
}

- (void)updateWithAnchor:(ARPlaneAnchor*)anchor
{
    self.anchor = anchor;
    [_debugVisualization updateWithAnchor:anchor];
    
    [self updateOcclusionNode];
}


- (void)showDebugVisualization:(BOOL)show
{
    if (show) {
        if (!_debugVisualization)
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                self.debugVisualization = [[PlaneDebugVisualization alloc]initWithAnchor:self.anchor];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                  
                    [self addChildNode:self.debugVisualization];
                });
            });
        }
    }else
    {
        [_debugVisualization removeFromParentNode];
        self.debugVisualization = nil;
    }
}



- (void)createOcclusionNode
{
    SCNPlane *occlusionPlane = [SCNPlane planeWithWidth:self.anchor.extent.x - 0.05 height:self.anchor.extent.z - 0.05];
    
    SCNMaterial *material = [[SCNMaterial alloc]init];
    material.colorBufferWriteMask = SCNColorMaskNone;
    material.doubleSided = YES;
    occlusionPlane.materials = @[material];
    
    self.occlusionNode = [[SCNNode alloc]init];
    self.occlusionNode.geometry = occlusionPlane;
    self.occlusionNode.transform = SCNMatrix4MakeRotation(-M_PI / 2.0, 1, 0, 0);
    self.occlusionNode.position = SCNVector3Make(self.anchor.center.x, self.occlusionPlaneVerticalOffset, self.anchor.center.z);
    
    [self addChildNode:_occlusionNode];
}

- (void)updateOcclusionNode
{
    if (!self.occlusionNode || ![self.occlusionNode.geometry isKindOfClass:[SCNPlane class]] ) {
        return;
    }
    
    SCNPlane *occlusionPlane = (SCNPlane*)self.occlusionNode.geometry;
    
    occlusionPlane.width = self.anchor.extent.x - 0.05;
    occlusionPlane.height = self.anchor.extent.z - 0.05;
    
    self.occlusionNode.position = SCNVector3Make(self.anchor.center.x, self.occlusionPlaneVerticalOffset, self.anchor.center.z);
    
}

@end
